import type { UserModelState } from '@/models/userModel';
import { register } from '@/services/home/api';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { ConnectRC } from '@umijs/max';
import { connect } from '@umijs/max';
import { Form, message } from 'antd';
import { forwardRef, useImperativeHandle } from 'react';

type LoginType = 'weixin' | 'account' | 'register';

interface Props {
  refInstance: any;
  usermodel: UserModelState;
}

interface RegisterFormT {
  username: string;
  password: string;
  nickname: string;
  email: string;
}

const Index: ConnectRC<Props> = (props) => {
  const {
    refInstance,
    usermodel: { isRegisterModal },
    dispatch,
  } = props;
  const [form] = Form.useForm<RegisterFormT>();

  useImperativeHandle(refInstance, () => ({}));
  return (
    <div>
      <ModalForm<RegisterFormT>
        form={form}
        autoFocusFirstInput
        open={isRegisterModal}
        width={550}
        modalProps={{
          onCancel: () => dispatch({ type: 'usermodel/changeIsRegisterModal', payload: false }),
        }}
        submitTimeout={2000}
        onFinish={async (values) => {
          const { code, message: msg } = await register(values);
          if (code === 200) {
            message.success('注册成功!');
            dispatch({ type: 'usermodel/changeIsRegisterModal', payload: false });
            dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: true });
            return true;
          }
          message.error(msg);
          return false;
        }}
      >
        <ProFormText
          name="username"
          label="用户名"
          placeholder={'请输入用户名'}
          fieldProps={{
            onChange: (e: any) => {
              form.setFieldValue('nickname', e.target.value);
            },
          }}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          label="密码"
          placeholder={'请输入用户密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <ProFormText
          name="nickname"
          tooltip="用作对外展示"
          label="昵称"
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
          placeholder="请输入昵称!"
        />
        <ProFormText
          name="email"
          tooltip="通知使用"
          label="关联邮箱"
          placeholder="请输入邮箱!"
          rules={[
            {
              type: 'email',
              message: '邮箱格式不正确!',
            },
          ]}
        />
      </ModalForm>
    </div>
  );
};
export default connect(({ usermodel }: { usermodel: UserModelState }) => ({
  usermodel,
}))(forwardRef((props: any, ref) => <Index {...props} refInstance={ref} />));
